import {reqCartList, reqDeleteCart, reqUpdateCheckCart} from '../api'
const state={
 cartInfoList:[]
}
const mutations= {
  CARTINFOLIST({commit}, cartInfoList) {
    state.cartInfoList = cartInfoList.data || []
  }
}
const getters={
 getCartInfoList(state){
   return state.cartInfoList[0]||{}
 }
}
const actions={
  updateAllChecked({dispatch,getters},isChecked) {
    let promiseAll=[]
     getters.getCartInfoList.cartInfoList.forEach(item => {
       let promise =  dispatch('changeChecked', {skuId: item.skuId, isChecked: isChecked})
       promiseAll.push(promise)
     })
    return Promise.all(promiseAll)//全多成功才能成功,不然所有请求操作多失败
  },
  deleteAllChecked({dispatch,getters}) {
    let promiseAll=[]
    getters.getCartInfoList.cartInfoList.forEach(item=>{
      let promise=item.isChecked==1?dispatch('deleteCart',item.skuId):''
      promiseAll.push(promise)
    })
    console.log(getters)
    return Promise.all(promiseAll)//全多成功才能成功,不然所有请求操作多失败
  },
  async getCartList({commit}){
    let result=await reqCartList()
    console.log(result.data)
    commit('CARTINFOLIST',result.data)
  },
  async deleteCart({commit},skuId){
    await reqDeleteCart(skuId)
  },
  async changeChecked({commit},{skuId,isChecked}){
    let result=await reqUpdateCheckCart(skuId,isChecked)
    console.log(result)
    if(result.data.code==200){
      return 'ok'
    }else {
      return Promise.reject(new Error('faile'))
    }
  }
}
export default {
  state,
  mutations,
  getters,
  actions
}
